package com.shawn.mobliesafe;

import android.app.ActivityManager;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.graphics.Color;
import android.os.Build;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.text.format.Formatter;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.shawn.bean.TaskInfo;
import com.shawn.engine.TaskEngine;
import com.shawn.utils.MyAsycnTaks;
import com.shawn.utils.TaskUtil;

import java.util.ArrayList;
import java.util.List;

public class TaskManagerActivity extends AppCompatActivity {

    private ListView lv_taskmanager_processes;
    private ProgressBar loading;
    private List<TaskInfo> list;
    //用户程序集合
    private List<TaskInfo> usertaskInfo;
    //系统程序的集合
    private List<TaskInfo> systemtaskInfo;
    private Myadapter myadapter;
    private TaskInfo taskInfo;
    //是否显示系统进程的标示
    private boolean isshowSystem = true;

    private TextView tv_taskmanager_processes;
    private TextView tv_taskmanager_freeandtotalram;
    private int processCount;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_task_manager);

        lv_taskmanager_processes = (ListView)findViewById(R.id.lv_taskmanager_processes);
        loading = (ProgressBar)findViewById(R.id.loading);

        tv_taskmanager_processes = (TextView)findViewById(R.id.tv_taskmanager_processes);
        tv_taskmanager_freeandtotalram = (TextView)findViewById(R.id.tv_taskmanager_freeandtotalram);
        // 设置显示数据
        // 获取相应的数据
        // 获取运行的进程个数
        processCount = TaskUtil.getProcessCount(getApplicationContext());
        tv_taskmanager_processes.setText("运行中进程:\n" + processCount + "个");
        // 获取剩余,总内存'
        long availableRam = TaskUtil.getAvailableRam(getApplicationContext());
        String availaRam = Formatter.formatFileSize(getApplicationContext(), availableRam);
        // 获取总内存
        // 根据不同的sdk版去调用不同的方法
        // 1.获取当前的sdk版本
        int sdkInt = Build.VERSION.SDK_INT;
        long totalRam;
        if(sdkInt >= 16) {
            totalRam = TaskUtil.getTotalRam(getApplicationContext());
        }else {
            totalRam = TaskUtil.getTotalRam();
        }
        String totRam = Formatter.formatFileSize(getApplicationContext(),
                totalRam);
        tv_taskmanager_freeandtotalram.setText("剩余/总内存:\n" + availaRam + "/"
                + totRam);

        //加载数据
        fillData();
        listviewItemClick();
    }

    private void listviewItemClick() {
        lv_taskmanager_processes.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if(position == 0 || position == usertaskInfo.size()+1) {
                    return;
                }
                if(position <= usertaskInfo.size()) {
                    taskInfo = usertaskInfo.get(position - 1);
                }else {
                    taskInfo = systemtaskInfo.get(position - usertaskInfo.size() - 2);
                }
                if(taskInfo.isChecked()) {
                    taskInfo.setChecked(false);
                }else {
                    if(!taskInfo.getPackageName().equals(getPackageName())) {
                        taskInfo.setChecked(true);
                    }
                }
                //4.更新界面
                //myadapter.notifyDataSetChanged();
                //只更新点击的条目
                ViewHolder viewHolder = (ViewHolder) view.getTag();
                viewHolder.cb_itemtaskmanager_ischecked.setChecked(taskInfo.isChecked());
            }
        });
    }

    private void fillData() {
        new MyAsycnTaks(){

            @Override
            public void preTask() {
                loading.setVisibility(View.VISIBLE);
            }

            @Override
            public void doinBack() {
                list = TaskEngine.getTaskAllInfo(TaskManagerActivity.this);
                usertaskInfo = new ArrayList<TaskInfo>();
                systemtaskInfo = new ArrayList<TaskInfo>();
                for (TaskInfo taskInfo : list){
                    if(taskInfo.isUser()) {
                        usertaskInfo.add(taskInfo);
                    }else {
                        systemtaskInfo.add(taskInfo);
                    }
                }
            }

            @Override
            public void postTask() {
                if(myadapter == null) {
                    myadapter = new Myadapter();
                    lv_taskmanager_processes.setAdapter(myadapter);
                }else {
                    myadapter.notifyDataSetChanged();
                }
                loading.setVisibility(View.INVISIBLE);
            }
        }.execute();

    }

    private class Myadapter extends BaseAdapter{

        @Override
        public int getCount() {
            return isshowSystem==true ? usertaskInfo.size() + 1 + systemtaskInfo.size() + 1 : usertaskInfo.size() + 1;
        }

        @Override
        public Object getItem(int position) {
            return list.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            if(position == 0) {
                TextView textView = new TextView(TaskManagerActivity.this);
                textView.setBackgroundColor(Color.GRAY);
                textView.setTextColor(Color.WHITE);
                textView.setText("用户进程("+usertaskInfo.size()+")");
                return textView;
            }else if(position == usertaskInfo.size()+1) {
                TextView textView = new TextView(TaskManagerActivity.this);
                textView.setBackgroundColor(Color.GRAY);
                textView.setTextColor(Color.WHITE);
                textView.setText("系统进程("+systemtaskInfo.size()+")");
                return textView;
            }

            View view;
            ViewHolder viewHolder;
            if(convertView != null && convertView instanceof RelativeLayout) {
                view = convertView;
                viewHolder = (ViewHolder) view.getTag();
            }else {
                view = View.inflate(getApplicationContext(),R.layout.item_taskmanager,null);
                viewHolder = new ViewHolder();
                viewHolder.iv_itemtaskmanager_icon = (ImageView) view.findViewById(R.id.iv_itemtaskmanager_icon);
                viewHolder.tv_itemtaskmanager_name = (TextView) view.findViewById(R.id.tv_itemtaskmanager_name);
                viewHolder.tv_itemtaskmanager_ram = (TextView) view.findViewById(R.id.tv_itemtaskmanager_ram);
                viewHolder.cb_itemtaskmanager_ischecked = (CheckBox) view.findViewById(R.id.cb_itemtaskmanager_ischecked);
                //将viewholer和view对象绑定
                view.setTag(viewHolder);
            }
            TaskInfo taskInfo = null;
            if(position <= usertaskInfo.size()) {
                taskInfo = usertaskInfo.get(position - 1);
            }else {
                taskInfo = systemtaskInfo.get(position - usertaskInfo.size() - 2);
            }
            if(taskInfo.getIcon() == null) {
                viewHolder.iv_itemtaskmanager_icon.setImageResource(R.mipmap.ic_default);
            }else {
                viewHolder.iv_itemtaskmanager_icon.setImageDrawable(taskInfo.getIcon());
            }
            //名称为空的可以设置为包名
            if(TextUtils.isEmpty(taskInfo.getName())) {
                viewHolder.tv_itemtaskmanager_name.setText(taskInfo.getPackageName());
            }else{
                viewHolder.tv_itemtaskmanager_name.setText(taskInfo.getName());
            }
            long ramSize = taskInfo.getRamSize();
            String formatFileSize = Formatter.formatFileSize(getApplicationContext(),ramSize);
            viewHolder.tv_itemtaskmanager_ram.setText("内存占用:"+formatFileSize);
            //因为checkbox的状态会跟着一起复用,所以一般要动态修改的控件的状态,不会跟着去复用,而是将状态保存到bean对象,在每次复用使用控件的时候
            //根据每个条目对应的bean对象保存的状态,来设置控件显示的相应的状态
            if(taskInfo.isChecked()) {
                viewHolder.cb_itemtaskmanager_ischecked.setChecked(true);
            }else {
                viewHolder.cb_itemtaskmanager_ischecked.setChecked(false);
            }
            //判断如果是我们的应用程序,就把checkbox隐藏,不是的话显示,在getview中有if必须有else
            if(taskInfo.getPackageName().equals(getPackageName())) {
                viewHolder.cb_itemtaskmanager_ischecked.setVisibility(View.INVISIBLE);
            }else {
                viewHolder.cb_itemtaskmanager_ischecked.setVisibility(View.VISIBLE);
            }
            return view;
        }
    }
    static class ViewHolder{
        ImageView iv_itemtaskmanager_icon;
        TextView tv_itemtaskmanager_name,tv_itemtaskmanager_ram;
        CheckBox cb_itemtaskmanager_ischecked;
    }

    /**
     * 全选
     * @param v
     */
    public void all(View v){
        for (TaskInfo taskinfo : usertaskInfo){
            if(!taskinfo.getPackageName().equals(getPackageName())) {
                taskinfo.setChecked(true);
            }
        }
        for (TaskInfo taskinfo : systemtaskInfo){
            taskinfo.setChecked(true);
        }
        myadapter.notifyDataSetChanged();
    }

    /**
     * 取消
     * @param v
     */
    public void cancel(View v){
        for (TaskInfo taskinfo : usertaskInfo){
            if(!taskinfo.getPackageName().equals(getPackageName())) {
                taskinfo.setChecked(false);
            }
        }
        for (TaskInfo taskinfo : systemtaskInfo){
            taskinfo.setChecked(false);
        }
        myadapter.notifyDataSetChanged();
    }

    /**
     * 清理
     * @param v
     */
    public void clear(View v){
        ActivityManager activityManager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
        //保存杀死进程信息的集合
        List<TaskInfo> deleteTaskInfo = new ArrayList<>();
        for (TaskInfo task : usertaskInfo){
            if(task.isChecked()) {
                activityManager.killBackgroundProcesses(task.getPackageName());
                deleteTaskInfo.add(task);
            }
        }
        for (TaskInfo task : systemtaskInfo){
            if(task.isChecked()) {
                activityManager.killBackgroundProcesses(task.getPackageName());
                deleteTaskInfo.add(task);
            }
        }
        long memory = 0;
        //遍历deleteTaskInfos,分别从userappinfo和systemappinfo中删除deleteTaskInfos中的数据
        for (TaskInfo taskinfo : deleteTaskInfo){
            if(taskinfo.isUser()) {
                usertaskInfo.remove(taskinfo);
            }else {
                systemtaskInfo.remove(taskinfo);
            }
            memory += taskinfo.getRamSize();
        }
        String deleteSize = Formatter.formatFileSize(getApplicationContext(),memory);
        Toast.makeText(getApplicationContext(),"共清理"+deleteTaskInfo.size()+"个进程,释放"+deleteSize+"内存空间",Toast.LENGTH_SHORT).show();

        // 更改运行中的进程个数以及剩余总内存
        processCount = processCount - deleteTaskInfo.size();
        tv_taskmanager_processes.setText("运行中进程:\n" + processCount + "个");
        // 更改剩余总内存,重新获取剩余总内存
        // 获取剩余,总内存
        long availableRam = TaskUtil.getAvailableRam(getApplicationContext());
        String availaRam = Formatter.formatFileSize(getApplicationContext(), availableRam);
        // 获取总内存
        // 根据不同的sdk版去调用不同的方法
        // 1.获取当前的sdk版本
        int sdkInt = Build.VERSION.SDK_INT;
        long totalRam;
        if(sdkInt >= 16) {
            totalRam = TaskUtil.getTotalRam(getApplicationContext());
        }else {
            totalRam = TaskUtil.getTotalRam();
        }
        String totRam = Formatter.formatFileSize(getApplicationContext(),
                totalRam);
        tv_taskmanager_freeandtotalram.setText("剩余/总内存:\n" + availaRam + "/"
                + totRam);

        deleteTaskInfo.clear();
        deleteTaskInfo = null;
        myadapter.notifyDataSetChanged();
    }

    /**
     * 设置
     * @param v
     */
    public void setting(View v){
        new AlertDialog.Builder(this)
                .setTitle("提示信息")
                .setMessage("是否显示系统进程？")
                .setPositiveButton("否", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        isshowSystem = false;
                        myadapter.notifyDataSetChanged();
                        dialog.dismiss();
                    }
                })
                .setNegativeButton("是", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        isshowSystem = true;
                        myadapter.notifyDataSetChanged();
                        dialog.dismiss();
                    }
                })
                .show();
    }
}
